package com.heiyu.api.controller;

import com.alibaba.fastjson.JSON;
import com.heiyu.api.request.UserLoginRequest;
import com.heiyu.api.request.VerifyCodePutRequest;
import com.heiyu.api.response.CommonResponse;
import com.heiyu.api.response.UserLoginResponse;
import com.heiyu.api.response.model.CommonModel;
import com.heiyu.api.response.model.UserLoginModel;
import com.heiyu.constants.ResponseMsgEnum;
import com.heiyu.controller.ApiBaseController;
import com.heiyu.dao.*;
import com.heiyu.entity.*;
import com.heiyu.utils.CacheKey;
import com.heiyu.utils.DateUtils;
import com.heiyu.utils.FileUtils;
import com.heiyu.utils.Md5Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@Api(description = "登陆相关")
@RestController
@RequestMapping("api/v1")
public class LoginController extends ApiBaseController {


    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private MessageInfoMapper messageInfoMapper;
    @Autowired
    private UserConfigMapper userConfigMapper;
    @Autowired
    private UserDeviceInfoMapper userDeviceInfoMapper;
    @Autowired
    private UserInviteMapper userInviteMapper;



    @ApiOperation(value = "login", notes = "登陆请求")
    @RequestMapping(value = "login",method = RequestMethod.POST)
    public UserLoginResponse login(@RequestBody UserLoginRequest request) {
        UserLoginResponse response = new UserLoginResponse();
        if(StringUtils.isEmpty(request.getDeviceID())){
            request.setDeviceID(getAddress());
        }else{
            if(!Md5Utils.md5(request.getDeviceID()+"version31").toLowerCase().equals(request.getSign())){
                response.error("签名错误");
                return response;
            }
        }

        String verifyCode = redisUtils.get(CacheKey.VERIFY_CODE + request.getTelphone());
        if (verifyCode == null) {
            response.error("验证码已失效");
        } else {
            redisUtils.del(CacheKey.VERIFY_CODE + request.getTelphone());
            if (!request.getVerifyCode().equals(verifyCode)) {
                response.error("验证码错误，请重新获取");
            } else {
                //判断用户是否存在
                UserInfo userInfo = new UserInfo();
                userInfo.setTelphone(request.getTelphone());
                List<UserInfo> userInfoList = this.userInfoMapper.selectList(userInfo);
                if (CollectionUtils.isEmpty(userInfoList)) {
                    //增加用户信息
                    userInfo.setStatus("1");
                    userInfo.setCreatedTime(new Date());
                    userInfo.setModifyTime(new Date());
                    userInfo.setIsDeleted("0");
                    userInfo.setToken(System.currentTimeMillis() + RandomStringUtils.random(10, false, true));
                    userInfo.setTokenLoseTime(DateUtils.getTargetDate(new Date(), 30));
                    userInfo.setPushId(request.getPushId());
                    this.userInfoMapper.insert(userInfo);
                    UserConfig config = new UserConfig();
                    config.setColorConfig("T");
                    config.setDefaultMoneyType("C");
                    config.setMessageConfig("F");
                    config.setId(userInfo.getId());
                    config.setUserId(userInfo.getId());
                    this.userConfigMapper.insert(config);
                    //判断是否活动邀请用户
                    try{
                        UserInvite userInvite = new UserInvite();
                        userInvite.setActivityId(1l);
                        userInvite.setInviteUserInfo(request.getTelphone());
                        userInvite.setStatus("1");
                        List<UserInvite> inviteList = this.userInviteMapper.selectList(userInvite);
                        if(CollectionUtils.isNotEmpty(inviteList)){
                            userInvite = inviteList.get(0);
                            userInvite.setStatus("2");
                            userInvite.setModifyTime(new Date());
                            this.userInviteMapper.updateById(userInvite);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                } else {
                    userInfo = userInfoList.get(0);
                    //清空原有的token数据
                    redisUtils.del(CacheKey.USER_INFO + userInfo.getToken());
                    //新增token信息
                    userInfo.setToken(System.currentTimeMillis() + RandomStringUtils.random(10, false, true));
                    userInfo.setTokenLoseTime(DateUtils.getTargetDate(new Date(), 30));
                    userInfo.setPushId(request.getPushId());
                    this.userInfoMapper.updateById(userInfo);
                }
                UserDeviceInfo deviceInfo = new UserDeviceInfo();
                deviceInfo.setUserId(userInfo.getId());
                deviceInfo.setDeviceId(request.getDeviceID());
                deviceInfo.setCreatedTime(new Date());
                deviceInfo.setModifyTime(new Date());
                deviceInfo.setIsDeleted("0");
                this.userDeviceInfoMapper.insert(deviceInfo);
                redisUtils.set(CacheKey.USER_INFO + userInfo.getToken(), JSON.toJSONString(userInfo));
                setHeader(AUTH_KEY, userInfo.getToken());
                response.success();
                response.setData(new UserLoginModel());
                response.getData().setToken(userInfo.getToken());
            }
        }
        return response;
    }

    @ApiOperation(value = "logout", notes = "登出")
    @RequestMapping(value = "logout", method = RequestMethod.POST)
    public CommonResponse logout() {
        CommonResponse response = new CommonResponse();

        UserInfo userInfo = getUser();
        if (userInfo == null) {
            response.error(ResponseMsgEnum.USER_NOT_LOGIN);
        } else {
            setHeader(AUTH_KEY, null);
            userInfo = this.userInfoMapper.selectPrimary(userInfo.getId());
            if (userInfo == null) {
                response.error("用户信息不存在");
            } else {
                redisUtils.del(CacheKey.USER_INFO + userInfo.getToken());
                userInfo.setToken("");
                this.userInfoMapper.updateById(userInfo);
                response.success();
            }
        }
        return response;
    }

    @ApiOperation(value = "verify/code/put", notes = "发送验证码")
    @ApiImplicitParam(name = "telphone", value = "手机号码")
    @RequestMapping(value = "verify/code/put",method = RequestMethod.POST)
    public CommonResponse verifyCodePut(@RequestBody VerifyCodePutRequest request) {
        CommonResponse response = new CommonResponse();
        if(!isMobile(request.getTelphone())){
            response.error("请输入正确的手机号");
            return response;
        }
        if(request.getTelphone().equals("13999999999")){
            redisUtils.set(CacheKey.VERIFY_CODE + request.getTelphone(), "8888",300);
            response.success();
            response.setData(new CommonModel());
            return response;
        }
        String diff = redisUtils.get(CacheKey.VERIFY_CODE_DIFF+request.getTelphone());
        if(StringUtils.isNotBlank(diff)){
            response.error("阁下手速有点快，系统跟不上啊！");
            return response;
        }
        redisUtils.set(CacheKey.VERIFY_CODE_DIFF+request.getTelphone(),"diffTime",60);
        long count = redisUtils.incr(CacheKey.VERIFY_CODE_CAL + request.getTelphone());
        if (count > 10) {
            response.error("短信发送次数过多，请明天再试");
            return response;
        }

        //生成验证码
        String verifyCode = RandomStringUtils.random(4, false, true);
        redisUtils.set(CacheKey.VERIFY_CODE + request.getTelphone(), verifyCode,300);
        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setParams(verifyCode);
        messageInfo.setToTelphone(request.getTelphone());
        messageInfo.setMsgType("1");
        messageInfo.setStatus("0");
        messageInfo.setSendTime(new Date());
        messageInfo.setContent("［链码］您的验证码是{param1},有效时间5分钟。");
         messageInfoMapper.insert(messageInfo);
         response.success();
         response.setData(new CommonModel());
        return response;
    }

}
